package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmUserDto;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser>implements WmUserService {
    //自媒体用户登录
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.检查用户名密码是否输入
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或者密码不存在");
        }
        //2.根据用户名查询对应用户
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }

        //3.判断用户密码和输入密码是否一致
        //dto.getPassword()是明文,需要和盐拼接,加密
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());

        if (!inputPwd.equals(wmUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //4.如果一致,颁发凭证,借助工具类
        String token = AppJwtUtil.getToken(wmUser.getId());

        //结果返回给前台,有user和token封装到data中

        Map result = new HashMap<>();//有两个参数就创建map
        result.put("token",token);
        wmUser.setPassword("");
        wmUser.setSalt("");
        //wmuser之前封装了vo返回给前端,把敏感的字段置为空
        result.put("user",wmUser);

        return ResponseResult.okResult(result);
    }
    //具体实现业务的层
}
